from uuid import uuid1
from flask import (Flask, render_template, request,
                   redirect, url_for, make_response)
import openai
import requests
from config import SECRET_KEY
import os

os.environ["http_proxy"] = "http://127.0.0.1:7890"
os.environ["https_proxy"] = "http://127.0.0.1:7890"

openai.api_key = SECRET_KEY

app = Flask(__name__)


@app.route('/', methods=['GET','POST'])
def index():
    # 接受post请求
    if request.method == 'POST': # 接收表单数据
        desc = request.form['desc']
        # 生成图片的核心代码
        response = openai.Image.create(
            prompt=desc,
            n=1,
            size="512x512"
        )
        image_url = response['data'][0]['url']
        return redirect(url_for("index", result=image_url))

    # 接受get请求
    result = request.args.get('result')
    return render_template('index.html', result=result)


@app.route('/download/')
def download():
    # 获取图片的url
    img_url = request.args.get('img_url')
    res = requests.get(img_url)
    if res.status_code != 200:
        return "请求失败"
    # 1. 根据URL爬取图片，获取图片的原始数据（二进制）res = requests.get(url)
    response = make_response(res.content)
    # 2. 附件形式， 类型是图片
    response.headers['Content-Type'] = 'image/png'
    response.headers['Content-Disposition'] = f"attachment;filename={uuid1()}.png"
    return response


if __name__ == '__main__':
    app.run(host='127.0.0.1',port='9090')
